<template>
  <a-modal
    :open="visible"
    title="补卡"
    width="500px"
    @ok="handleOk"
    @cancel="handleCancel"
    @update:open="(val) => emit('update:visible', val)"
  >
    <a-form :model="formData" :rules="rules" ref="formRef" layout="vertical">
      <a-form-item label="房间号" name="roomNumber">
        <a-input v-model:value="formData.roomNumber" disabled />
      </a-form-item>

      <a-form-item label="原手牌" name="originalHandCard">
        <a-input v-model:value="formData.originalHandCard" disabled />
      </a-form-item>

      <a-form-item label="新手牌" name="newHandCard">
        <a-input
          v-model:value="formData.newHandCard"
          placeholder="请输入新手牌号"
          @keyup.enter="handleOk"
        />
      </a-form-item>

      <a-form-item label="补卡原因" name="reason">
        <a-select v-model:value="formData.reason" placeholder="请选择补卡原因">
          <a-select-option value="lost">手牌丢失</a-select-option>
          <a-select-option value="damaged">手牌损坏</a-select-option>
          <a-select-option value="other">其他原因</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="备注" name="notes">
        <a-textarea
          v-model:value="formData.notes"
          placeholder="请输入备注"
          :rows="3"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { message } from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';

interface Room {
  id: string;
  number: string;
  type: string;
  status: string;
  capacity: number;
  occupied: number;
  handCard?: string;
}

interface Props {
  visible: boolean;
  room?: Room | null;
}

interface Emits {
  (e: 'update:visible', value: boolean): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const formRef = ref<FormInstance>();
const formData = ref({
  roomNumber: '',
  originalHandCard: '',
  newHandCard: '',
  reason: '',
  notes: '',
});

const rules = {
  newHandCard: [{ required: true, message: '请输入新手牌号' }],
  reason: [{ required: true, message: '请选择补卡原因' }],
};

// 监听房间变化
watch(
  () => props.room,
  (room) => {
    if (room) {
      formData.value = {
        roomNumber: room.number,
        originalHandCard: room.handCard || '',
        newHandCard: '',
        reason: '',
        notes: '',
      };
    }
  },
  { immediate: true },
);

const handleOk = async () => {
  try {
    await formRef.value?.validate();

    // 这里调用补卡API
    message.success('补卡成功');
    emit('update:visible', false);
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

const handleCancel = () => {
  emit('update:visible', false);
};
</script>
